package cn.ylxn.dataAtructureAndAlgorithm;

public class ArrayQueue {
    public static void main(String[] args) {
        MyArrayQueueFinally aFinally = new MyArrayQueueFinally(3);
        aFinally.addQueue(5);
        aFinally.addQueue(6);
        aFinally.showList();
    }
}
class MyArrayQueue{
    private int maxSize;//数组最大容量
    private  int front;//队列头
    private int rear;//队列尾
    private int[] array; //队列，存储数组
    //创建队列
    public MyArrayQueue(int max){
        maxSize = max;
        array = new int[maxSize];
        front = -1;//指向队列头
        rear = -1;//指向队列尾
    }

    //判断队列是否满
    public boolean isFull(){
        return rear==maxSize-1;
    }
    //判断队列是否为空
    public boolean isEmpty(){
        return rear==front;
    }
    public void addQueue(int n ){
        if (isFull()){
            System.out.println("队列满");
            return;
        }
        rear++; //rear后移
        array[rear]=n;
    }
    public int getQueue(){
        if (isEmpty()){
            System.out.println("队列空");
            throw new RuntimeException("队列为空");
        }
        front++;
        return array[front];
    }
    public void showList(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i = 0; i < array.length; i++) {
            System.out.printf("arr[%d]=%d\n",i,array[i]);
        }
    }
    //显示队列头
    public int showHead(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return array[front+1];
    }
}

class MyArrayQueueFinally{
    private int maxSize;//数组最大容量
    private int front;//队列头
    private int rear;//队列尾
    private int[] array; //队列，存储数组
    //创建队列
    public MyArrayQueueFinally(int max){
        maxSize = max;
        array = new int[maxSize];
    }

    //判断队列是否满
    public boolean isFull(){
        return (rear+1)%maxSize==front;
    }
    //判断队列是否为空
    public boolean isEmpty(){
        return rear==front;
    }
    public void addQueue(int n ){
        if (isFull()){
            System.out.println("队列满");
            return;
        }
        array[rear]=n;
        rear=(rear+1)%maxSize;
    }
    public int getQueue(){
        if (isEmpty()){
            System.out.println("队列空");
            throw new RuntimeException("队列为空");
        }
        int value = array[front];
        front=(front+1)%maxSize;
        return value;
    }
    public void showList(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i = front; i < front+ size() ; i++) {
            System.out.printf("arr[%d]=%d\n",i%maxSize,array[i%maxSize]);
        }
    }
    //求出当前队列有效个数
    public int size(){
        return (rear+maxSize-front)%maxSize;
    }
    //显示队列头
    public int showHead(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return array[front];
    }
}
